import { Judge, Contestant, Score, ScoreResponse, ContestantResponse, JudgeCreate, ContestantCreate, ScoreCreate } from './types'

const API_BASE_URL = '/api'

async function apiCall<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`
  const response = await fetch(url, {
    headers: {
      'Content-Type': 'application/json',
      ...(options.headers || {})
    },
    ...options
  })
  if (!response.ok) {
    let errorMessage = `API调用失败: ${response.status} ${response.statusText}`
    try {
      const errorData = await response.json()
      if (errorData.detail) {
        errorMessage = errorData.detail
      }
    } catch (e) {
      // 忽略JSON解析错误
    }
    throw new Error(errorMessage)
  }
  return response.json()
}

export const judgeApi = {
  create: (judge: JudgeCreate): Promise<Judge> =>
    apiCall<Judge>('/judges/', { method: 'POST', body: JSON.stringify(judge) }),
  getAll: (): Promise<Judge[]> => apiCall<Judge[]>('/judges/'),
  getCount: (): Promise<{ total_judges: number }> => apiCall<{ total_judges: number }>('/judges/count'),
  delete: (judgeId: number): Promise<{ message: string }> =>
    apiCall<{ message: string }>(`/judges/${judgeId}`, { method: 'DELETE' })
}

export const contestantApi = {
  create: (contestant: ContestantCreate): Promise<Contestant> =>
    apiCall<Contestant>('/contestants/', { method: 'POST', body: JSON.stringify(contestant) }),
  getAll: (): Promise<Contestant[]> => apiCall<Contestant[]>('/contestants/'),
  getActive: (): Promise<Contestant | null> => apiCall<Contestant | null>('/contestants/active'),
  getActiveAdjustedAverage: (): Promise<{ contestant: { id: number; number: string; name: string } | null; adjusted_average: number; total_scores: number }> =>
    apiCall('/contestants/active/adjusted-average'),
  activate: (contestantId: number): Promise<{ message: string }> =>
    apiCall<{ message: string }>(`/contestants/${contestantId}/activate`, { method: 'POST' }),
  delete: (contestantId: number): Promise<{ message: string }> =>
    apiCall<{ message: string }>(`/contestants/${contestantId}`, { method: 'DELETE' })
}

export const scoreApi = {
  create: (score: ScoreCreate): Promise<Score> =>
    apiCall<Score>('/scores/', { method: 'POST', body: JSON.stringify(score) }),
  getByContestant: (contestantId: number): Promise<ScoreResponse[]> =>
    apiCall<ScoreResponse[]>(`/scores/contestant/${contestantId}`),
  getRanking: (): Promise<ContestantResponse[]> => apiCall<ContestantResponse[]>('/scores/ranking'),
  checkJudgeScore: (judgeId: number, contestantId: number): Promise<{ has_scored: boolean }> =>
    apiCall<{ has_scored: boolean }>(`/scores/judge/${judgeId}/contestant/${contestantId}/check`),
  clearJudgeScore: (judgeId: number, contestantId: number): Promise<{ message: string }> =>
    apiCall<{ message: string }>(`/scores/judge/${judgeId}/contestant/${contestantId}`, { method: 'DELETE' }),
  clearJudgeScoreByName: (judgeName: string, contestantId: number): Promise<{ message: string }> =>
    apiCall<{ message: string }>(`/scores/judge/${encodeURIComponent(judgeName)}/contestant/${contestantId}`, { method: 'DELETE' })
}
